import json

from django.core.paginator import Paginator
from django.db.models import Count
from django.http import JsonResponse
from django.views import View
from django.views.decorators.http import require_http_methods

from field.models import *
from system.models import Address
from .models import Resource, ResourceSerializer


# Create your views here.
# 处理资源数据 ============================================

class SearchView(View):
    def post(self, req):
        try:
            data = json.loads(req.body.decode('utf-8'))

            pageNum = data['pageNum']  # 当前页
            pageSize = data['pageSize']  # 每页大小
            city = data['city']
            county = data['county']
            town = data['town']
            forest_class = data['forestClass']
            ecological_zone = data['ecologicalZone']

            queryset = Resource.objects.all().order_by('address__city', 'address__county', 'ecological_zone',
                                                       'forest_class', 'origin', 'dominant_tree_species')
            # 先构建基础查询条件（必选条件：city）
            if city:
                queryset = queryset.filter(address__city__in=city)
            if county:  # 如果county列表有元素（非空）
                queryset = queryset.filter(address__county__in=county)
            if town:  # 如果county列表有元素（非空）
                queryset = queryset.filter(address__town__in=town)
            if forest_class:
                queryset = queryset.filter(forest_class__name__in=forest_class)
            if ecological_zone:
                queryset = queryset.filter(ecological_zone__name__in=ecological_zone)

            # 获取查询集
            # queryset = Resource.objects.filter(address__city__in=city, address__county__in=county)
            total = queryset.count()

            # 分页
            paginator = Paginator(queryset, pageSize)
            dataPage = paginator.page(pageNum)

            # 序列化数据 - 传递查询集给序列化器
            serializer = ResourceSerializer(dataPage.object_list, many=True)

            return JsonResponse({'code': 200, 'data': serializer.data, 'total': total})

        # 捕获未预料的异常
        except Exception as e:
            return JsonResponse({
                'code': 500,
                'msg': f'服务器错误：{str(e)}'  # 生产环境可简化为"服务器内部错误"
            })


class SelectView(View):
    def post(self, req):
        try:
            data = json.loads(req.body.decode('utf-8'))
            city = data['city']
            county = data['county']

            queryset = Resource.objects.all()
            city_list = queryset.values_list('address__city', flat=True).distinct()
            county_list = queryset.values_list('address__county', flat=True).distinct()
            town_list = queryset.values_list('address__town', flat=True).distinct()
            forest_class_list = queryset.values_list('forest_class__name', flat=True).distinct()
            ecological_zone_list = queryset.values_list('ecological_zone__name', flat=True).distinct()

            if city:
                queryset = queryset.filter(address__city__in=city)
                county_list = queryset.values_list('address__county', flat=True).distinct()
                town_list = queryset.values_list('address__town', flat=True).distinct()

            if county:
                queryset = queryset.filter(address__county__in=county)
                town_list = queryset.values_list('address__town', flat=True).distinct()

            return JsonResponse({
                'code': 200,
                'data': {'cityList': list(city_list),
                         'countyList': list(county_list),
                         'townList': list(town_list),
                         'forestClassList': list(forest_class_list),
                         'ecologicalZoneList': list(ecological_zone_list),
                         }
            })

        # 捕获未预料的异常
        except Exception as e:
            print(f'服务器错误：{str(e)}')
            return JsonResponse({
                'code': 500,
                'msg': f'服务器错误：{str(e)}'  # 生产环境可简化为"服务器内部错误"
            })


# 新增或修改
class SaveView(View):
    def post(self, request):
        try:
            data = json.loads(request.body.decode('utf-8'))
            print(data)
            # 如果需要确保地址唯一，可以使用以下代码
            address, created = Address.objects.get_or_create(
                province=data['province'],
                city=data['city'],
                county=data['county'],
                town=data['town'],
                village=data['village'],
                # detail=data['detail', '']
            )

            if data['id'] == -1:  # 添加
                obj = Resource(address=address,
                               vegetation_ecological_zone=VegetationEcologicalZone.objects.get(
                                   id=data['vegetation_ecological_zone']),
                               ecological_engineering_zone=EcologicalEngineeringZone.objects.get(
                                   id=data['ecological_engineering_zone']),
                               forest_class=ForestClass.objects.get(id=data['forest_class']),
                               ecological_zone=EcologicalZone.objects.get(id=data['ecological_zone']),
                               dominant_tree_species=TreeSpecies.objects.get(id=data['dominant_tree_species']),
                               origin=Origin.objects.get(id=data['origin']),
                               age_group=AgeGroup.objects.get(id=data['age_group']),
                               area=data['area'], stock=data['stock'], stock_per_ha=data['stock_per_ha'],
                               mean_tree_height=data['mean_tree_height'], mean_dbh=data['mean_dbh'],
                               forest_stand_biomass=data['forest_stand_biomass'], coefficient=data['coefficient'],
                               remark=data['remark'])
                obj.save()
            else:  # 修改
                obj = Resource(id=data['id'], address=address,
                               vegetation_ecological_zone=VegetationEcologicalZone.objects.get(
                                   id=data['vegetation_ecological_zone']),
                               ecological_engineering_zone=EcologicalEngineeringZone.objects.get(
                                   id=data['ecological_engineering_zone']),
                               forest_class=ForestClass.objects.get(id=data['forest_class']),
                               ecological_zone=EcologicalZone.objects.get(id=data['ecological_zone']),
                               dominant_tree_species=TreeSpecies.objects.get(id=data['dominant_tree_species']),
                               origin=Origin.objects.get(id=data['origin']),
                               age_group=AgeGroup.objects.get(id=data['age_group']),
                               area=data['area'], stock=data['stock'], stock_per_ha=data['stock_per_ha'],
                               mean_tree_height=data['mean_tree_height'], mean_dbh=data['mean_dbh'],
                               forest_stand_biomass=data['forest_stand_biomass'], coefficient=data['coefficient'],
                               remark=data['remark'])
                obj.save()
            return JsonResponse({'code': 200, 'msg': '执行成功！'})
        # 捕获其他未预料的异常（作为兜底）
        except Exception as e:
            print(f'服务器错误：{str(e)}')
            return JsonResponse({
                'code': 500,
                'msg': f'服务器错误：{str(e)}'  # 生产环境可简化为"服务器内部错误"
            })


# 根据id获取记录
class GetResource(View):
    def get(self, req):
        try:
            obj = Resource.objects.get(id=int(req.GET['id']))
            print(ResourceSerializer(obj).data)
            return JsonResponse({'code': 200, 'data': ResourceSerializer(obj).data})
        # 捕获数据库查询异常（如修改时id不存在）
        except Resource.DoesNotExist:
            return JsonResponse({
                'code': 404,
                'msg': f'异常：ID为 {req.GET['id']} 的记录不存在!'
            })
        # 捕获其他未预料的异常（作为兜底）
        except Exception as e:
            return JsonResponse({
                'code': 500,
                'msg': f'服务器错误：{str(e)}'  # 生产环境可简化为"服务器内部错误"
            })


class CountView(View):
    def get(self, req):
        try:
            result = Resource.objects.values(
                'address__city'  # 按category字段分组
            ).annotate(
                count=Count('id')  # 计算每组的记录数（用id或*均可）
            ).order_by('address__city')  # 按分类名称排序（可选）
            label, data = [], []
            for item in result:
                label.append(item['address__city'])
                data.append(item['count'])
            zyfb = {'label': label, 'data': data}

            ############################################################
            result = Resource.objects.values('age_group__name').annotate(count=Count('id')).order_by('age_group__name')
            nlz = []
            for item in result:
                nlz.append({'name': item['age_group__name'], 'value': item['count']})

            ############################################################
            result = Resource.objects.values('ecological_zone__name').annotate(count=Count('id')).order_by(
                'ecological_zone__name')
            # print('统计结果：', result)
            stfq = []
            for item in result:
                stfq.append({'name': item['ecological_zone__name'], 'value': item['count']})
            return JsonResponse({'code': 200, 'zyfb': zyfb, 'nlz': nlz, 'stfq': stfq})

        # 捕获其他未预料的异常（作为兜底）
        except Exception as e:
            return JsonResponse({
                'code': 500,
                'msg': f'服务器错误：{str(e)}'  # 生产环境可简化为"服务器内部错误"
            })


@require_http_methods(["GET"])
def ResourceList(request):
    response = {}
    try:
        resources = Resource.objects.all().order_by('address__city', 'address__county', 'ecological_zone',
                                                    'forest_class', 'origin', 'dominant_tree_species')

        resource_list = []

        for resource in resources:
            resource_list.append({
                'id': resource.id,
                'province': resource.address.province if resource.address else None,
                'city': resource.address.city if resource.address else None,
                'county': resource.address.county if resource.address else None,
                'town': resource.address.town if resource.address else None,
                'village': resource.address.village if resource.address else None,
                'vegetation_ecological_zone': resource.vegetation_ecological_zone.name if resource.vegetation_ecological_zone else None,
                'ecological_engineering_zone': resource.ecological_engineering_zone.name if resource.ecological_engineering_zone else None,
                # 只返回名称，避免序列化整个对象
                'forest_class': resource.forest_class.name if resource.forest_class else None,
                'forest_level': resource.forest_class.level if resource.forest_class else None,
                'ecological_zone': resource.ecological_zone.name if resource.ecological_zone else None,
                'ecological_zone_2': resource.ecological_zone_2,
                'dominant_tree_species': resource.dominant_tree_species.name if resource.dominant_tree_species else None,
                'origin': resource.origin.name if resource.origin else None,
                'age_group': resource.age_group.name if resource.age_group else None,
                'area': resource.area,
                'stock': resource.stock,
                'stock_per_ha': resource.stock_per_ha,
                'mean_tree_height': resource.mean_tree_height,
                'mean_dbh': resource.mean_dbh,
                'forest_stand_biomass': resource.forest_stand_biomass,
                'coefficient': resource.coefficient,
                'remark': resource.remark,
            })

        response['msg'] = 'Get resource list success!'
        response['code'] = 200
        # response['data'] = list(resources.values())
        response['data'] = resource_list
    except Exception as e:
        response['msg'] = str(e)
        response['code'] = 500
    return JsonResponse(response)


@require_http_methods(["GET", "POST"])
def ResourceAdd(request):
    response = {}
    try:
        resource = Resource()
        data = None
        if request.method == 'POST':
            # 根据Content-Type解析数据
            if request.content_type == 'application/json':
                data = json.loads(request.body)
            else:
                data = request.POST
        elif request.method == 'GET':
            data = request.GET
        # 获取外键对象
        # address = Address.objects.get(province=data.get('province'), city=data.get('city'),
        #                               county=data.get('county'), town=data.get('town'),
        #                               village=data.get('village'), detail=data.get('detail')) if data.get('province') else None
        # # 如果地址不存在，则创建一个新的地址对象
        # if not address:
        #     address = Address.objects.create(
        #         province=data.get('province', '广西'),
        #         city=data.get('city', ''),
        #         county=data.get('county', ''),
        #         town=data.get('town', ''),
        #         village=data.get('village', ''),
        #         detail=data.get('detail', '')
        #     )
        print('@@@', data['newResource'])
        data = data['newResource']
        # 如果需要确保地址唯一，可以使用以下代码
        address, created = Address.objects.get_or_create(
            province=data['province'],
            city=data['city'],
            county=data['county'],
            town=data['town'],
            village=data['village'],
            # detail=data['detail', '']
        )

        vegetation_ecological_zone = VegetationEcologicalZone.objects.get(id=data['vegetation_ecological_zone'])
        ecological_engineering_zone = EcologicalEngineeringZone.objects.get(id=data['ecological_engineering_zone'])
        forest_class = ForestClass.objects.get(id=data['forest_class'])
        ecological_zone = EcologicalZone.objects.get(id=data['ecological_zone'])
        dominant_tree_species = TreeSpecies.objects.get(id=data['dominant_tree_species'])
        origin = Origin.objects.get(id=data['origin'])
        age_group = AgeGroup.objects.get(id=data['age_group'])

        # 设置资源对象的属性
        # resource.province = data.get('province', '广西')
        # resource.city = data.get('city', '')
        # resource.county = data.get('county', '')
        # resource.town = data.get('town', '')
        # resource.village = data.get('village', '')

        resource.address = address
        resource.vegetation_ecological_zone = vegetation_ecological_zone
        resource.ecological_engineering_zone = ecological_engineering_zone
        resource.forest_class = forest_class
        resource.ecological_zone = ecological_zone
        resource.ecological_zone_2 = data['ecological_zone_2']
        resource.dominant_tree_species = dominant_tree_species
        resource.origin = origin
        resource.age_group = age_group
        resource.area = float(data['area'])
        resource.stock = float(data['stock'])
        resource.stock_per_ha = float(data['stock_per_ha'])
        resource.mean_tree_height = float(data['mean_tree_height'])
        resource.mean_dbh = float(data['mean_dbh'])
        resource.forest_stand_biomass = float(data['forest_stand_biomass'])
        resource.coefficient = float(data['coefficient'])
        resource.remark = data['remark']

        resource.save()
        response['msg'] = 'Resource added successfully!'
        response['code'] = 200

    except Exception as e:
        response['msg'] = str(e)
        response['code'] = 500
    return JsonResponse(response)


def ResourceUpdate(request):
    response = {}
    try:
        data = None
        if request.method == 'POST':
            # 根据Content-Type解析数据
            if request.content_type == 'application/json':
                data = json.loads(request.body)
            else:
                data = request.POST
        elif request.method == 'GET':
            data = request.GET

        # 判断资源是否已存在
        if Resource.objects.filter(id=data.get('id')).exists():
            item = Resource.objects.get(id=data.get('id'))

            # 如果需要确保地址唯一，可以使用以下代码
            address, created = Address.objects.get_or_create(
                province=data.get('province', ''),
                city=data.get('city', ''),
                county=data.get('county', ''),
                town=data.get('town', ''),
                village=data.get('village', ''),
                detail=data.get('detail', '')
            )

            # item.province = data.get('province')
            # item.city = data.get('city')
            # item.county = data.get('county')
            # item.town = data.get('town')
            # item.village = data.get('village')
            item.address = address
            # item.vegetation_ecological_zone = data.get('vegetation_ecological_zone')
            item.vegetation_ecological_zone = VegetationEcologicalZone.objects.get(
                id=data.get('vegetation_ecological_zone')) if data.get('vegetation_ecological_zone') else None
            item.ecological_engineering_zone = EcologicalEngineeringZone.objects.get(
                id=data.get('ecological_engineering_zone')) if data.get('ecological_engineering_zone') else None
            item.forest_class = ForestClass.objects.get(id=data.get('forest_class')) if data.get(
                'forest_class') else None
            item.ecological_zone = EcologicalZone.objects.get(id=data.get('ecological_zone')) if data.get(
                'ecological_zone') else None
            item.ecological_zone_2 = data.get('ecological_zone_2')
            item.dominant_tree_species = TreeSpecies.objects.get(id=data.get('dominant_tree_species')) if data.get(
                'dominant_tree_species') else None
            item.origin = Origin.objects.get(id=data.get('origin')) if data.get('origin') else None
            item.age_group = AgeGroup.objects.get(id=data.get('age_group')) if data.get('age_group') else None
            item.area = data.get('area')
            item.stock = data.get('stock')
            item.stock_per_ha = data.get('stock_per_ha')
            item.mean_tree_height = data.get('mean_tree_height')
            item.mean_dbh = data.get('mean_dbh')
            item.forest_stand_biomass = data.get('forest_stand_biomass')
            item.coefficient = data.get('coefficient')
            item.remark = data.get('remark')

            item.save()  # 更新所有字段
            response['msg'] = '更新成功！'
            response['code'] = 200
        else:
            response['msg'] = '该资源已经不存在！'
            response['code'] = 500
            return JsonResponse(response)

    except Exception as e:
        response['msg'] = str(e)
        response['code'] = 500
        print('Exception')
    return JsonResponse(response)


from rest_framework.decorators import api_view, permission_classes
from rest_framework.permissions import AllowAny


@api_view(['POST'])
@permission_classes([AllowAny])
def ResourceImport(request):
    response = {}
    try:
        data = None
        erroe_data = []
        if request.method == 'POST':
            # 根据Content-Type解析数据
            if request.content_type == 'application/json':
                data = json.loads(request.body)
            else:
                data = request.POST
        data = data.get('dataSource')
        # print(data)
        for item in data:
            resource = Resource()

            # 如果需要确保地址唯一，可以使用以下代码
            address, created = Address.objects.get_or_create(
                province=item.get('province', ''),
                city=item.get('city', ''),
                county=item.get('county', ''),
                town=item.get('town', ''),
                village=item.get('village', ''),
                detail=item.get('detail', '')
            )

            vegetation_ecological_zone = VegetationEcologicalZone.objects.get(
                name=item.get('vegetation_ecological_zone'))
            ecological_engineering_zone = EcologicalEngineeringZone.objects.get(
                name=item.get('ecological_engineering_zone'))
            forest_class = ForestClass.objects.get(name=item.get('forest_class'), level=item.get('forest_level'))
            ecological_zone = EcologicalZone.objects.get(name=item.get('ecological_zone'))
            dominant_tree_species = TreeSpecies.objects.get(name=item.get('dominant_tree_species'))
            origin = Origin.objects.get(name=item.get('origin'))
            age_group = AgeGroup.objects.get(name=item.get('age_group'))

            resource.address = address
            resource.vegetation_ecological_zone = vegetation_ecological_zone
            resource.ecological_engineering_zone = ecological_engineering_zone
            resource.forest_class = forest_class
            resource.ecological_zone = ecological_zone
            resource.ecological_zone_2 = item.get('ecological_zone_2', '')
            resource.dominant_tree_species = dominant_tree_species
            resource.origin = origin
            resource.age_group = age_group

            resource.year = float(item.get('year', ''))
            resource.area = float(item.get('area', 0.0))
            resource.stock = float(item.get('stock', 0.0))
            resource.stock_per_ha = float(item.get('stock_per_ha', 0.0))
            resource.mean_tree_height = float(item.get('mean_tree_height', 0.0))
            resource.mean_dbh = float(item.get('mean_dbh', 0.0))
            resource.forest_stand_biomass = float(item.get('forest_stand_biomass', 0.0))
            resource.coefficient = float(item.get('coefficient', 0.0))
            resource.remark = item.get('remark', '')

            resource.save()

            response['msg'] = 'Resource import successfully!'
            response['code'] = 200
            response['erroe_data'] = erroe_data

    except Exception as e:
        response['msg'] = str(e)
        response['code'] = 500
    return JsonResponse(response)


@require_http_methods(["GET", "POST"])
def ResourceDelete(request):
    response = {}
    try:
        resource_id = None
        if request.method == 'GET':
            resource_id = request.GET['id']
        elif request.method == 'POST':
            resource_id = request.POST['id']

        if not resource_id:
            response['msg'] = 'Resource ID is required!'
            response['code'] = 500
            return JsonResponse(response)

        resource = Resource.objects.get(id=resource_id)
        resource.delete()
        response['msg'] = 'Resource deleted successfully!'
        response['code'] = 200
    except Resource.DoesNotExist:
        response['msg'] = 'Resource not found!'
        response['code'] = 500
    except Exception as e:
        response['msg'] = str(e)
        response['code'] = 500
    return JsonResponse(response)


@require_http_methods(["GET"])
def ResourceTotals(request):
    response = {}
    try:
        resources = Resource.objects.all().order_by('address__city', 'address__county', 'ecological_zone',
                                                    'forest_class', 'origin', 'dominant_tree_species')

        resource_list = ResourceSerializer(resources, many=True).data

        # 按城市、省份、县、生态区、森林类别、起源、主要树种分组统计资源数量
        totals_list = []
        # 获取所有唯一的city值
        unique_cities = list(set(item['city'] for item in resource_list))
        index = 1
        for city in unique_cities:
            city_resources = [item for item in resource_list if item['city'] == city]

            # 县 ============================================
            unique_county = list(set(item['county'] for item in city_resources))
            for county in unique_county:
                county_resources = [item for item in city_resources if item['county'] == county]

                # ecological_zone ============================================
                unique_zones = list(set(item['ecological_zone_name'] for item in county_resources))
                for zone in unique_zones:
                    zone_resources = [item for item in county_resources if item['ecological_zone_name'] == zone]

                    # forest_class ============================================
                    unique_forest_classes = list(set(item['forest_class_name'] for item in zone_resources))
                    for forest_class in unique_forest_classes:
                        class_resources = [item for item in zone_resources if item['forest_class_name'] == forest_class]

                        # origin ============================================
                        unique_origins = list(set(item['origin_name'] for item in class_resources))
                        for origin in unique_origins:
                            origin_resources = [item for item in class_resources if item['origin_name'] == origin]

                            # dominant_tree_species ============================================
                            unique_species = list(set(item['dominant_tree_species_name'] for item in origin_resources))
                            for species in unique_species:
                                species_resources = [item for item in origin_resources if
                                                     item['dominant_tree_species_name'] == species]
                                ag_1 = len([item for item in species_resources if item['age_group_name'] == '幼龄林'])
                                ag_2 = len([item for item in species_resources if item['age_group_name'] == '中龄林'])
                                ag_3 = len([item for item in species_resources if item['age_group_name'] == '近熟林'])
                                ag_4 = len([item for item in species_resources if item['age_group_name'] == '成熟林'])
                                ag_5 = len([item for item in species_resources if item['age_group_name'] == '过熟林'])
                                totals_list.append({
                                    'index': index,
                                    'city': city,
                                    'county': county,
                                    'ecological_zone_2': zone,
                                    'forest_class': forest_class,
                                    'forest_class_level': species_resources[0]['forest_class_level'],
                                    'origin': origin,
                                    'dominant_tree_species': species,
                                    'ag_1_count': ag_1,
                                    'ag_2_count': ag_2,
                                    'ag_3_count': ag_3,
                                    'ag_4_count': ag_4,
                                    'ag_5_count': ag_5,
                                    'total_count': ag_1 + ag_2 + ag_3 + ag_4 + ag_5
                                })
                                index += 1

                        totals_list.append({
                            'index': '', 'city': city, 'county': county, 'ecological_zone_2': zone,
                            'forest_class': forest_class + "（合计）",
                            'origin': '', 'dominant_tree_species': '',
                            'ag_1_count': '', 'ag_2_count': '', 'ag_3_count': '', 'ag_4_count': '', 'ag_5_count': '',
                            'total_count': len(class_resources)
                        })

                    totals_list.append({
                        'index': '', 'city': city,
                        'county': county, 'ecological_zone_2': zone + "（合计）",
                        'forest_class': '', 'origin': '', 'dominant_tree_species': '',
                        'ag_1_count': '', 'ag_2_count': '', 'ag_3_count': '', 'ag_4_count': '', 'ag_5_count': '',
                        'total_count': len(zone_resources)
                    })
                    # index += 1

            # 计算该城市的总面积和总蓄积量
            # total_area = sum(item['area'] for item in city_resources if item['area'] is not None)
            # total_stock = sum(item['stock'] for item in city_resources if item['stock'] is not None)

        response['msg'] = 'Get resource list success!'
        response['code'] = 200
        # response['data'] = list(resources.values())
        response['data'] = totals_list
    except Exception as e:
        response['msg'] = str(e)
        response['code'] = 500
    return JsonResponse(response)


class TotalsView(View):
    def post(self, req):
        try:
            data = json.loads(req.body.decode('utf-8'))

            city = data['city']
            county = data['county']
            town = data['town']
            forest_class = data['forestClass']
            ecological_zone = data['ecologicalZone']

            queryset = Resource.objects.all()

            # 先构建基础查询条件（必选条件：city）
            if city:
                queryset = queryset.filter(address__city__in=city)
            if county:  # 如果county列表有元素（非空）
                queryset = queryset.filter(address__county__in=county)
            if town:  # 如果county列表有元素（非空）
                queryset = queryset.filter(address__town__in=town)
            if forest_class:
                queryset = queryset.filter(forest_class__name__in=forest_class)
            if ecological_zone:
                queryset = queryset.filter(ecological_zone__name__in=ecological_zone)

            # 获取查询集
            queryset = queryset.order_by('address__city', 'address__county', 'ecological_zone',
                                         'forest_class', 'origin', 'dominant_tree_species')
            total = queryset.count()

            # # 分页
            # paginator = Paginator(queryset, pageSize)
            # dataPage = paginator.page(pageNum)

            # 序列化数据 - 传递查询集给序列化器
            # serializer = ResourceSerializer(dataPage.object_list, many=True)
            #
            # resources = Resource.objects.all().order_by('address__city', 'address__county', 'ecological_zone',
            #                                             'forest_class', 'origin', 'dominant_tree_species')

            resource_list = ResourceSerializer(queryset, many=True).data

            # 按城市、省份、县、生态区、森林类别、起源、主要树种分组统计资源数量
            totals_list = []
            # 获取所有唯一的city值
            unique_cities = list(set(item['city'] for item in resource_list))
            index = 1
            for city in unique_cities:
                city_resources = [item for item in resource_list if item['city'] == city]

                # 县 ============================================
                unique_county = list(set(item['county'] for item in city_resources))
                for county in unique_county:
                    county_resources = [item for item in city_resources if item['county'] == county]

                    # ecological_zone ============================================
                    unique_zones = list(set(item['ecological_zone_name'] for item in county_resources))
                    for zone in unique_zones:
                        zone_resources = [item for item in county_resources if item['ecological_zone_name'] == zone]

                        # forest_class ============================================
                        unique_forest_classes = list(set(item['forest_class_name'] for item in zone_resources))
                        for forest_class in unique_forest_classes:
                            class_resources = [item for item in zone_resources if
                                               item['forest_class_name'] == forest_class]

                            # origin ============================================
                            unique_origins = list(set(item['origin_name'] for item in class_resources))
                            for origin in unique_origins:
                                origin_resources = [item for item in class_resources if item['origin_name'] == origin]

                                # dominant_tree_species ============================================
                                unique_species = list(
                                    set(item['dominant_tree_species_name'] for item in origin_resources))
                                for species in unique_species:
                                    species_resources = [item for item in origin_resources if
                                                         item['dominant_tree_species_name'] == species]
                                    ag_1 = len(
                                        [item for item in species_resources if item['age_group_name'] == '幼龄林'])
                                    ag_2 = len(
                                        [item for item in species_resources if item['age_group_name'] == '中龄林'])
                                    ag_3 = len(
                                        [item for item in species_resources if item['age_group_name'] == '近熟林'])
                                    ag_4 = len(
                                        [item for item in species_resources if item['age_group_name'] == '成熟林'])
                                    ag_5 = len(
                                        [item for item in species_resources if item['age_group_name'] == '过熟林'])
                                    totals_list.append({
                                        'index': index,
                                        'city': city,
                                        'county': county,
                                        'ecological_zone_2': zone,
                                        'forest_class': forest_class,
                                        'forest_class_level': species_resources[0]['forest_class_level'],
                                        'origin': origin,
                                        'dominant_tree_species': species,
                                        'ag_1_count': ag_1,
                                        'ag_2_count': ag_2,
                                        'ag_3_count': ag_3,
                                        'ag_4_count': ag_4,
                                        'ag_5_count': ag_5,
                                        'total_count': ag_1 + ag_2 + ag_3 + ag_4 + ag_5
                                    })
                                    index += 1

                            totals_list.append({
                                'index': '', 'city': city, 'county': county, 'ecological_zone_2': zone,
                                'forest_class': forest_class + "（合计）",
                                'origin': '', 'dominant_tree_species': '',
                                'ag_1_count': '', 'ag_2_count': '', 'ag_3_count': '', 'ag_4_count': '',
                                'ag_5_count': '',
                                'total_count': len(class_resources)
                            })

                        totals_list.append({
                            'index': '', 'city': city,
                            'county': county, 'ecological_zone_2': zone + "（合计）",
                            'forest_class': '', 'origin': '', 'dominant_tree_species': '',
                            'ag_1_count': '', 'ag_2_count': '', 'ag_3_count': '', 'ag_4_count': '', 'ag_5_count': '',
                            'total_count': len(zone_resources)
                        })
                        # index += 1

                # 计算该城市的总面积和总蓄积量
                # total_area = sum(item['area'] for item in city_resources if item['area'] is not None)
                # total_stock = sum(item['stock'] for item in city_resources if item['stock'] is not None)

            #     response['msg'] = 'Get resource list success!'
            #     response['code'] = 200
            #     # response['data'] = list(resources.values())
            #     response['data'] = totals_list
            # except Exception as e:
            #     response['msg'] = str(e)
            #     response['code'] = 500
            # return JsonResponse(response)

            return JsonResponse({'code': 200, 'data': totals_list, 'total': total})

        # 捕获未预料的异常
        except Exception as e:
            return JsonResponse({
                'code': 500,
                'msg': f'服务器错误：{str(e)}'  # 生产环境可简化为"服务器内部错误"
            })
